import pymongo
from utils.config import Config


class MongoDB:

    # 初始化连接
    def __init__(
            self,
            ip=Config.MONGODB_IP,
            port=Config.MONGODB_PORT,
            user=Config.MONGODB_USER,
            pwd=Config.MONGODB_PWD):
        client = pymongo.MongoClient(
            f"mongodb://{user}:{pwd}@{ip}:{port}")
        self.db = client[Config.MONGODB_DB_NAME]

    # 封装插入方法,指定集合封装到方法中，便于选择不同集合（表）
    def insert_many(self, collection, query):
        res = self.db[collection]
        return res.insert_many(query)

    def insert_one(self,collection,query):
        res = self.db[collection]
        return res.insert_one(query)


    def find_all(self,collection):
        res = self.db[collection]

        listres = []
        
        res = res.find()
        for one in res:
            listres.append(one)
        return listres

    def find_one(self,collection,query):
        res = self.db[collection]

        res = res.find_one(query)
        return res
    
    # 封装查询方法
    def find(self, collection, query, many=False):
        res = self.db[collection]

        if many == False:
            res = res.find_one(query)
            return res
        elif many == True:
            listres = []
            res = res.find(query)
            for one in res:
                listres.append(one)
            return listres
        

    # 封装更新方法
    def update(self, collection, myquery, newvalue, many=False):
        res = self.db[collection]
        if many == False:
            res.update_one(myquery, {'$set': newvalue})
        elif many == True:
            res.update_many(myquery, {'$set': newvalue})

    # 封装删除方法
    def delete(self, collection, query, many=False):
        res = self.db[collection]
        if many == False:
            res.delete_one(query)
        elif many == True:
            res.delete_many(query)



